package user

import (
	"errors"
	"parking-lot-go-dingding/controller"
	"parking-lot-go-dingding/model/dingtalk/system"
	"parking-lot-go-dingding/model/view"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Login(c *gin.Context) {

	requestStruct := struct {
		CorpId string `json:"corp_id"`
		Userid string `json:"userid"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		controller.Fail(c, "json接收失败")
		return
	}

	//查询钉钉用户信息
	var dingtalkSystemDepartmentUserStruct system.DingtalkSystemDepartmentUserStruct
	if _, err := dingtalkSystemDepartmentUserStruct.First(requestStruct.CorpId, requestStruct.Userid); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			controller.Fail(c, "用户数据获取失败")
			return
		} else {
			controller.Fail(c, err.Error())
			return
		}
	}

	//查询用户信息
	var membersDingtalkViewStruct view.MembersDingtalkViewStruct
	member, err := membersDingtalkViewStruct.First(map[string]interface{}{
		"member_dingtalk_corpid": requestStruct.CorpId,
		"member_dingtalk_userid": requestStruct.Userid,
	})
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		controller.Fail(c, err.Error())
		return
	}

	//管理员身份判断
	var isAdmin bool
	var dingtalkSystemAdminStruct system.DingtalkSystemAdminStruct
	_, err = dingtalkSystemAdminStruct.First(requestStruct.CorpId, requestStruct.Userid)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			isAdmin = false
		} else {
			controller.Fail(c, err.Error())
			return
		}
	} else {
		isAdmin = true
	}

	controller.Success(c, map[string]interface{}{
		"is_admin":   isAdmin,
		"dept_id":    dingtalkSystemDepartmentUserStruct.DepartmentId,
		"member_id":  member.MemberId,
		"showMantle": !isAdmin,
	})
}
